<template>
  <div class="chat-sidebar-wrapper">
    <!-- 悬浮控制器 -->
    <div class="floating-toolbar" :class="{ hidden: showHistoryPanel }">
      <div class="pill">
        <button
          class="pill-btn history-toggle-btn"
          @click="toggleHistoryPanel"
          :title="toggleButtonTitle">
          <svg-icon icon-class="sidebar" class-name="icon-svg" />
        </button>
        <button
          class="title-image-btn"
          @click="handleNewChat"
          :title="appTitle">
          <img :src="titleImage" :alt="appTitle" class="title-image" />
        </button>
      </div>
    </div>

    <!-- 历史抽屉 -->
    <transition name="slideIn">
      <div v-if="showHistoryPanel" class="history-drawer" ref="historyDrawer">
        <div class="drawer-header">
          <div class="title-image-btn drawer-title-btn" @click="handleNewChat" :title="appTitle">
            <img :src="titleImage" :alt="appTitle" class="title-image" />
          </div>
          <button class="close-btn" @click="toggleHistoryPanel">
            <svg-icon icon-class="sidebar" class-name="close-icon" />
          </button>
        </div>
        <div class="drawer-content">
          <!-- 快速新建按钮 -->
          <div class="quick-action-bar">
            <button class="quick-new-chat-btn" @click="handleNewChat">
              <h3>开始新对话</h3>
            </button>
          </div>
          <div class="history-list">
            <div v-for="group in historyGroups" :key="group.label" class="history-group">
              <div class="group-label">{{ group.label }}</div>
              <div
                v-for="item in group.items"
                :key="item.id"
                class="history-item"
                :class="{ active: currentConversationId === item.id }"
                @click="handleLoadConversation(item.id)">
                <div class="history-item-content">
                  <i class="el-icon-document"></i>
                  <span class="history-title">{{ item.name || defaultConversationName }}</span>
                </div>
                <button
                  class="delete-btn"
                  @click.stop="handleDeleteChat(item.id)"
                  title="删除">
                  <i class="el-icon-delete"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'ChatSidebar',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    conversations: {
      type: Array,
      default: () => []
    },
    currentConversationId: {
      type: String,
      default: null
    },
    appTitle: {
      type: String,
      default: '智能问答助手'
    },
    // 标题图片配置
    titleImage: {
      type: String,
      default: () => require('@/assets/img/assistant-logo.png')
    },
    defaultConversationName: {
      type: String,
      default: '新建工作'
    },
    toggleButtonTitle: {
      type: String,
      default: '打开侧边栏'
    }
  },
  data() {
    return {
      showHistoryPanel: this.visible
    }
  },
  computed: {
    historyGroups() {
      const groups = {
        today: { label: '今天', items: [] },
        week: { label: '7 天内', items: [] },
        month: { label: '30 天内', items: [] },
        older: { label: '更早', items: [] }
      }

      const now = Date.now()
      // 原始时间分组逻辑（保留备份，便于回溯）
      // this.conversations.forEach(item => {
      //   // 智能处理时间戳：自动判断是秒还是毫秒
      //   let timestamp = item.updated_at
      //
      //   // 如果是字符串，尝试解析
      //   if (typeof timestamp === 'string') {
      //     timestamp = new Date(timestamp).getTime()
      //   } else if (typeof timestamp === 'number') {
      //     // 判断是秒还是毫秒：如果小于1e12，认为是秒（2001年9月9日之后的秒数）
      //     if (timestamp < 1e12) {
      //       timestamp = timestamp * 1000
      //     }
      //   }
      //
      //   // 计算天数差异（按时间差）
      //   const daysDiff = Math.floor((now - timestamp) / (1000 * 60 * 60 * 24))
      //
      //   if (daysDiff === 0) {
      //     groups.today.items.push(item)
      //   } else if (daysDiff <= 7) {
      //     groups.week.items.push(item)
      //   } else if (daysDiff <= 30) {
      //     groups.month.items.push(item)
      //   } else {
      //     groups.older.items.push(item)
      //   }
      // })

      // 新时间分组逻辑：按“自然日”分组，并增强时间戳兼容性（数字字符串/秒/毫秒/Date 等）
      this.conversations.forEach(item => {
        // 优先使用 updated_at，没有则退回 created_at
        const rawTimestamp = item.updated_at || item.created_at
        // 前端日志：观察后端返回的时间字段及其类型（仅在非生产环境打印）
        if (process.env.NODE_ENV !== 'production') {
          // eslint-disable-next-line no-console
          console.log('[ChatSidebar] conversation timestamp', {
            id: item.id,
            updated_at: item.updated_at,
            created_at: item.created_at,
            typeofUpdatedAt: typeof item.updated_at,
            typeofCreatedAt: typeof item.created_at
          })
        }
        const timestamp = this.normalizeTimestamp(rawTimestamp)

        // 无法解析时间的，统一归为“更早”
        if (!timestamp) {
          groups.older.items.push(item)
          return
        }

        const itemDate = new Date(timestamp)
        const nowDate = new Date(now)

        // 以本地时区的“当天零点”为界，按自然日计算差值，避免跨时区/24 小时滑动窗口导致的误差
        const startOfToday = new Date(
          nowDate.getFullYear(),
          nowDate.getMonth(),
          nowDate.getDate()
        )
        const startOfItemDay = new Date(
          itemDate.getFullYear(),
          itemDate.getMonth(),
          itemDate.getDate()
        )

        const daysDiff = Math.floor(
          (startOfToday.getTime() - startOfItemDay.getTime()) / (1000 * 60 * 60 * 24)
        )

        if (daysDiff === 0) {
          groups.today.items.push(item)
        } else if (daysDiff > 0 && daysDiff <= 7) {
          groups.week.items.push(item)
        } else if (daysDiff > 7 && daysDiff <= 30) {
          groups.month.items.push(item)
        } else {
          groups.older.items.push(item)
        }
      })

      return Object.values(groups).filter(group => group.items.length > 0)
    }
  },
  watch: {
    visible(newVal) {
      this.showHistoryPanel = newVal
    },
    showHistoryPanel(newVal) {
      this.$emit('update:visible', newVal)
    }
  },
  methods: {
    // 新增：统一时间戳解析工具，兼容多种格式
    normalizeTimestamp(value) {
      if (!value) return null

      let timestamp = value

      if (timestamp instanceof Date) {
        const t = timestamp.getTime()
        return isNaN(t) ? null : t
      }

      const type = typeof timestamp

      if (type === 'number') {
        // 数字时间戳：小于 1e12 认为是秒，大于等于 1e12 认为是毫秒
        if (timestamp < 1e12) {
          return timestamp * 1000
        }
        return timestamp
      }

      if (type === 'string') {
        const str = timestamp.trim()

        // 纯数字字符串：按长度判断秒/毫秒
        if (/^\d+$/.test(str)) {
          let num = parseInt(str, 10)
          if (str.length <= 10) {
            num = num * 1000
          }
          return num
        }

        // 通用日期字符串（包含时区/ISO 等）
        const date = new Date(str)
        const t = date.getTime()
        return isNaN(t) ? null : t
      }

      return null
    },
    toggleHistoryPanel() {
      this.showHistoryPanel = !this.showHistoryPanel
    },
    handleNewChat() {
      this.$emit('new-chat')
    },
    handleLoadConversation(conversationId) {
      this.$emit('load-conversation', conversationId)
    },
    handleDeleteChat(conversationId) {
      this.$emit('delete-chat', conversationId)
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-sidebar-wrapper {
  position: relative;
}

/* 悬浮工具栏 */
.floating-toolbar {
  position: fixed;
  top: 102px;
  left: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 2000;
  --btn-size: 32px;
  --padding: 8px;
}

.brand-icon {
  color: var(--c-law-blue, #3b82f6);
  font-size: 24px;
  height: calc(var(--btn-size) + 2 * var(--padding));
  width: calc(var(--btn-size) + 2 * var(--padding));
  display: flex;
  align-items: flex-end;
}

.brand-svg {
  width: 100%;
  height: 100%;
  display: block;
  color: var(--c-law-blue, #3b82f6);
}

.pill {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  background: #ffffff;
  border: 1px solid rgba(0,0,0,.06);
  border-radius: 24px;
  padding: var(--padding) 12px;
  box-shadow: 0 8px 24px rgba(17,24,39,.10);
}

/* 纯图片按钮样式 */
.title-image-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: none;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 8px;
  transition: all 0.2s ease;

  &:hover {
    background: rgba(59, 130, 246, 0.1);
    transform: translateY(-1px);
  }

  &:active {
    transform: translateY(0);
  }

  &.drawer-title-btn {
    flex: 1;
    margin: 0 8px;
    padding: 8px 12px;

    &:hover {
      background: rgba(59, 130, 246, 0.08);
    }
  }
}

/* 标题图片样式 */
.title-image {
  height: 24px;
  width: auto;
  object-fit: contain;
  display: block;

  /* 悬浮工具栏中的尺寸 */
  .pill & {
    height: 20px;
    max-width: 140px;
  }

  /* 抽屉中的尺寸 */
  .drawer-title-btn & {
    height: 88px;
    max-width: 180px;
  }
}

/* 基础按钮样式 */
.pill-btn {
  width: var(--btn-size);
  height: var(--btn-size);
  border-radius: 50%;
  background: transparent;
  border: 1px solid #d1d5db;
  color: #111827;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all .15s ease;

  &:hover {
    background: #f3f4f6;
    border-color: var(--c-law-blue, #3b82f6);
    color: var(--c-law-blue, #3b82f6);
  }
}

.icon-svg {
  width: 18px;
  height: 18px;
  display: block;
}

.floating-toolbar.hidden {
  opacity: 0;
  pointer-events: none;
  transform: translateY(-4px);
  transition: opacity .15s ease, transform .15s ease;
}

/* 历史抽屉 */
.history-drawer {
  position: fixed;
  top: 80px;
  left: 0;
  bottom: 0;
  width: 400px;
  background: #ffffff;
  border-right: 1px solid var(--c-border, #cbd5e1);
  box-shadow: 4px 0 16px rgba(0,0,0,.08);
  display: flex;
  flex-direction: column;
  z-index: 1000;
}

.drawer-header {
  height: 60px;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e5e7eb;
  background: #fff;
  overflow: hidden;
}

.close-btn {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  border: none;
  background: transparent;
  color: #6b7280;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  &:hover {
    background: #f3f4f6;
  }
}

.close-icon {
  width: 24px;
  height: 24px;
}

.drawer-content {
  flex: 1;
  padding: 14px 10px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

/* 过渡动画 */
.slideIn-enter-active,
.slideIn-leave-active {
  transition: transform .2s ease, opacity .2s ease;
}

.slideIn-enter,
.slideIn-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}

/* 快速操作栏 */
.quick-action-bar {
  padding: 0 8px 12px 8px;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 12px;
}

.quick-new-chat-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 16px;
  background: #f8fafc;
  border: 1px dashed #cbd5e1;
  border-radius: 10px;
  color: #64748b;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background: #e0f2fe;
    border-color: #3b82f6;
    color: #3b82f6;
    border-style: solid;
  }

  h3 {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
  }
}

/* 历史列表 */
.history-list {
  display: flex;
  flex-direction: column;
 /* gap: 12px;*/
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  overflow-x: hidden;
  scrollbar-width: thin;
  scrollbar-color: transparent transparent;
  transition: scrollbar-color 0.3s ease;

  &:hover,
  &:active {
    scrollbar-color: #d1d5db rgba(0, 0, 0, 0.05);
  }

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    border-radius: 4px;
    margin: 4px 0;
  }

  &::-webkit-scrollbar-thumb {
    background: transparent;
    border-radius: 4px;
    border: 1px solid transparent;
    min-height: 40px;
    transition: background 0.3s ease, border-color 0.3s ease;
  }

  &:hover::-webkit-scrollbar-thumb {
    background: #d1d5db;
    border-color: rgba(0, 0, 0, 0.05);
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #9ca3af;
  }

  &::-webkit-scrollbar-thumb:active {
    background: #6b7280;
  }
}

.history-group {
  display: flex;
  flex-direction: column;

  margin-bottom: 12px;
}

.group-label {
  font-size: 12px;
  color: #9ca3af;
  font-weight: 500;
  padding: 4px 8px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 4px;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.2s;
  position: relative;
  border: 1px solid transparent;
  margin-bottom: 4px;

  &:hover {
    background: #e0f2fe;
    border-color: #bae6fd;
  }

  &.active {
    background: linear-gradient(180deg, #dbeafe 0%, #bfdbfe 100%);
    border-color: #93c5fd;
    box-shadow: inset 0 0 0 2px rgba(59, 130, 246, 0.15);
  }
}

.history-item-content {
  display: flex;
  align-items: center;

  flex: 1;
  overflow: hidden;
}

.history-item-content i {
  font-size: 16px;
  color: #6b7280;
  flex-shrink: 0;
  margin-right: 8px;
}

.history-title {
  font-size: 13px;
  color: #374151;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-left: 6px;
}

.delete-btn {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  border: none;
  background: transparent;
  color: #ef4444;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s, background 0.2s;

  &:hover {
    background: #fee2e2;
  }
}

.history-item:hover .delete-btn {
  opacity: 1;
}
</style>
